// 留学贴士路由
const express = require('express');
const router = express.Router();
const Tip = require('../models/Tip');
const User = require('../models/User');
const { Op } = require('sequelize');

/**
 * 获取贴士列表
 * @route GET /api/tips
 * @description 获取留学贴士列表，支持分页、搜索和分类筛选
 * @access Public
 */
router.get('/', async (req, res) => {
  try {
    const { page = 1, size = 10, keyword = '', type = '' } = req.query;
    const offset = (page - 1) * size;
    
    const whereCondition = {
      status: 1 // 只返回正常状态的贴士
    };
    
    // 关键词搜索
    if (keyword) {
      whereCondition[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    // 分类筛选
    if (type && type !== '全部') {
      whereCondition.type = type;
    }
    
    const { count, rows } = await Tip.findAndCountAll({
      where: whereCondition,
      include: [{
        model: User,
        as: 'author',
        attributes: ['nickName', 'avatarUrl']
      }],
      limit: parseInt(size),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });
    
    // 格式化内容，截取部分内容作为简介
    const formattedTips = rows.map(tip => ({
      ...tip.toJSON(),
      summary: tip.content.replace(/<[^>]*>/g, '').substring(0, 100) + '...'
    }));
    
    res.status(200).json({
      success: true,
      data: formattedTips,
      total: count,
      page: parseInt(page),
      totalPages: Math.ceil(count / size)
    });
  } catch (error) {
    console.error('获取贴士列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取贴士详情
 * @route GET /api/tips/:id
 * @description 获取单个贴士的详细信息
 * @access Public
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查询贴士详情
    const tip = await Tip.findByPk(id, {
      include: [{
        model: User,
        as: 'author',
        attributes: ['nickName', 'avatarUrl']
      }]
    });
    
    if (!tip) {
      return res.status(404).json({ message: '贴士不存在' });
    }
    
    // 增加浏览次数
    await tip.update({ viewCount: tip.viewCount + 1 });
    
    res.status(200).json({ success: true, data: tip });
  } catch (error) {
    console.error('获取贴士详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 创建贴士
 * @route POST /api/tips
 * @description 创建新的留学贴士
 * @access Private
 */
router.post('/', async (req, res) => {
  try {
    const userId = req.user?.id || 1; // 临时处理，实际应用中应从token中获取
    const { title, content, type, coverImage } = req.body;
    
    // 验证必填字段
    if (!title || !content || !type) {
      return res.status(400).json({ message: '缺少必要的贴士信息' });
    }
    
    // 创建贴士
    const tip = await Tip.create({
      title,
      content,
      type,
      coverImage,
      authorId: userId
    });
    
    res.status(201).json({ success: true, data: tip, message: '贴士发布成功' });
  } catch (error) {
    console.error('创建贴士失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 点赞贴士
 * @route POST /api/tips/:id/like
 * @description 用户点赞贴士
 * @access Private
 */
router.post('/:id/like', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查询贴士
    const tip = await Tip.findByPk(id);
    
    if (!tip) {
      return res.status(404).json({ message: '贴士不存在' });
    }
    
    // 增加点赞次数
    await tip.update({ likeCount: tip.likeCount + 1 });
    
    res.status(200).json({ success: true, message: '点赞成功', likeCount: tip.likeCount + 1 });
  } catch (error) {
    console.error('点赞失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

/**
 * 获取热门贴士
 * @route GET /api/tips/hot
 * @description 获取热门贴士列表
 * @access Public
 */
router.get('/hot', async (req, res) => {
  try {
    // 获取浏览量最高的前10条贴士
    const hotTips = await Tip.findAll({
      where: { status: 1 },
      include: [{
        model: User,
        as: 'author',
        attributes: ['nickName']
      }],
      limit: 10,
      order: [['viewCount', 'DESC']]
    });
    
    // 格式化内容
    const formattedTips = hotTips.map(tip => ({
      ...tip.toJSON(),
      summary: tip.content.replace(/<[^>]*>/g, '').substring(0, 80) + '...'
    }));
    
    res.status(200).json({ success: true, data: formattedTips });
  } catch (error) {
    console.error('获取热门贴士失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;